package com.dashan.servlets;

import static com.dashan.Constants.NICKNAME;
import static com.dashan.Constants.PWDSHA;
import static com.dashan.Constants.SUCCESS;
import static com.dashan.Constants.USERNAME;
import static com.dashan.servlets.Parameter.Option.Required;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.jdo.JDODataStoreException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dashan.backend.DashanException;
import com.dashan.backend.FriendManager;
import com.dashan.backend.datastore.DsUser;
import com.dashan.backend.datastore.UserDao;

@SuppressWarnings("serial")
public class CreateUserServlet extends DashanServlet {
    
    @Override
    public ArrayList<Parameter> getParameterList() {
        ArrayList<Parameter> res = super.getParameterList();
        res.add(new Parameter(USERNAME, Required, String.class));
        res.add(new Parameter(NICKNAME, String.class, "New User"));
        res.add(new Parameter(PWDSHA, Required, String.class));
        return res;
    }
    
    @Override
    public String getUrlPattern() {
        return "/createuser";
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        UserDao dao = new UserDao();
        try {
            DsUser user = dao.createUser(params.get(USERNAME).stringValue(), 
                    params.get(NICKNAME).stringValue(), 
                    params.get(PWDSHA).stringValue());
            FriendManager.initializeUserGroup(user);
        } catch (JDODataStoreException e) {
            throw new ServletException("Cannot create user: " + e.getMessage());
        } catch (DashanException e) {
            throw new ServletException("Cannot create user: " + e.getMessage());
        } finally {
            dao.commit();
        }
        
        resp.getWriter().println(SUCCESS);
    }

}
